import { useState, useEffect, useMemo } from 'react'
import { useMeta, useMailTypeOptions, useMailTemplates, useCookies } from '@/stores'
import { Space, Button, Table, Tooltip, DialogPlugin, Select, Textarea, message, Loading } from 'tdesign-react'
import TongtoolDetailDrawer from './TongtoolDetailDrawer'
import MailDetailDrawer from './MailDetailDrawer'
import {
  RiMailOpenFill,
  RiMailCheckFill,
  RiSendPlaneFill,
  RiTruckFill,
  RiDeleteBin6Fill,
  RiAccountPinCircleFill
} from 'react-icons/ri'
import KeepAlive from 'react-activation'
import { apis, ApiRequest } from '@/service'
import { useTranslation } from 'react-i18next'
import { Conf as Store } from 'electron-conf/renderer'
import ExcelExporter from '@/utils/common/ExcelExporter'
import dayjs from 'dayjs'

import styles from './index.module.less'

import type { TFunction } from 'i18next'
import type { PrimaryTableCol } from 'tdesign-react'

type PropsType = {
  t: TFunction
}

const electronStore = new Store()

const {
  getMailListApi,
  getMailHistoryListApi,
  finishMailApi,
  getPersonListApi,
  assignMailApi,
  checkMailBeforeSendApi,
  sendMailApi
} = apis.JSYService

const Home = (_: PropsType) => {

  const {
    mailTopTypeOptions,
    mailSecondTypeOptions,
  } = useMailTypeOptions()

  const {
    mailTemplates
  } = useMailTemplates()

  const {
    JSYCookie
  } = useCookies()

  const [tableData, setTableData] = useState<any[]>([])
  const [total, setTotal] = useState(0)
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    paging: true
  })
  const [tongtoolDetailDrawerVisible, setTongtoolDetailDrawerVisible] = useState(false)
  const [mailDetailDrawerVisible, setMailDetailDrawerVisible] = useState(false)
  const [clickedRowIndex, setClickedRowIndex] = useState(-1)
  const [getMailsDetailLoading, setGetMailsDetailLoading] = useState(false)
  const [refundTableData, setRefundTableData] = useState<any[]>([])

  const queryParams = {
    orderStatus: 102002, // 分配给我的订单
    page: 1,
    limit: 200,
    sc: "2",
    tagIds: [],
    tagCatIds: [],
    emailIds: [],
    replyUserIds: [],
    checkUserIds: [],
    overdue: null,
    nowAssignmentId: "",
    mailVersion: null,
    mailVersionRel: null,
    includeHistory: 0,
    sort: 1,
    pageSize: 200
  }

  const headers = {
    "accept": "application/json, text/plain, */*",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
    "authorization": JSYCookie,
    "content-type": "application/json;charset=UTF-8",
    "priority": "u=1, i",
    "sec-ch-ua": "\"Chromium\";v=\"136\", \"Microsoft Edge\";v=\"136\", \"Not.A/Brand\";v=\"99\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Windows\"",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
  }

  /**  获取邮件列表 */
  const {
    data: mailListData, send: getMailList, loading: mailListLoading
  } = ApiRequest({
    api: {
      ...getMailListApi,
      useMock: true,
    },
    params: queryParams,
    headers
  })

  /** 获取邮件历史记录 */
  const {
    send: getMailHistoryList
  } = ApiRequest({
    api: {
      ...getMailHistoryListApi,
      // useMock: true
    },
    params: {},
    headers
  })

  /** 完成邮件 */
  const {
    send: finishMail, onSuccess: finishMailSuccess, loading: finishMailLoading
  } = ApiRequest({
    api: {
      ...finishMailApi,
      // useMock: true
    },
    params: {},
    headers
  })

  /** 获取人员信息 */
  const {
    send: getPersonList
  } = ApiRequest({
    api: {
      ...getPersonListApi,
      // useMock: true
    },
    params: {},
    headers
  })

  /** 分配邮件 */
  const {
    send: assignMail, loading: assignMailLoading
  } = ApiRequest({
    api: {
      ...assignMailApi,
      // useMock: true
    },
    params: {},
    headers
  })

  /** 发送邮件前检查 */
  const {
    send: checkMailBeforeSend, loading: checkMailBeforeSendLoading
  } = ApiRequest({
    api: {
      ...checkMailBeforeSendApi,
      // useMock: true
    },
    params: {},
    headers
  })

  /** 发送邮件 */
  const {
    send: sendMail, loading: sendMailLoading
  } = ApiRequest({
    api: {
      ...sendMailApi,
      // useMock: true
    },
    params: {},
    headers
  })

  useEffect(() => {
    if (!mailListData || mailListLoading) {
      return
    } else if (mailListData && mailListData.code === 401001) {
      message.error('即时语系统凭证失效，请填写新的Cookie')
    } else {
      setTableDataByMailListData()
    }
  }, [mailListLoading])

  useEffect(() => {
    window.electron.ipcRenderer.on('m2r-query-single-order', (_, orderList, dataIndex, note) => {
      if (!orderList) {
        message.error(note)
        return
      }
      if (orderList.length === 0) {
        message.warning(note)
        return
      }
      const _tableData = structuredClone(tableData)
      _tableData[dataIndex]['tongtoolOrderList'] = orderList
      if (orderList[0]) {
        _tableData[dataIndex]['reply'] = _tableData[dataIndex]['reply']
          ?.replaceAll('${trackingNo}', orderList[0].trackingNo)
          ?.replaceAll('${trackingInfo}', orderList[0].trackingInfo)
          ?.replaceAll('${refundMoney10}', (orderList[0].TOTALPRICE * 0.1).toFixed(2))
          ?.replaceAll('${refundMoney20}', (orderList[0].TOTALPRICE * 0.2).toFixed(2))
          ?.replaceAll('${refundMoney25}', (orderList[0].TOTALPRICE * 0.25).toFixed(2))
          ?.replaceAll('${refundMoney30}', (orderList[0].TOTALPRICE * 0.3).toFixed(2))
          ?.replaceAll('${refundMoney50}', (orderList[0].TOTALPRICE * 0.5).toFixed(2))
          ?.replaceAll('${refundMoney80}', (orderList[0].TOTALPRICE * 0.8).toFixed(2))
          ?.replaceAll('${refundMoney100}', (orderList[0].TOTALPRICE * 1).toFixed(2))
      }
      setTableData(_tableData)
      message.success(note)
    })
    window.electron.ipcRenderer.on('m2r-query-all-order', (_, allTongtoolOrderList, note) => {
      if (!allTongtoolOrderList) {
        message.error(note)
      } else {
        const _tableData = structuredClone(tableData)
        for (let i = 0; i < allTongtoolOrderList.length; i++) {
          _tableData[i]['tongtoolOrderList'] = allTongtoolOrderList[i]
          if (_tableData[i]['tongtoolOrderList'][0]) {
            _tableData[i]['reply'] = _tableData[i]['reply']
              ?.replaceAll('${trackingNo}', _tableData[i]['tongtoolOrderList'][0].trackingNo)
              ?.replaceAll('${trackingInfo}', _tableData[i]['tongtoolOrderList'][0].trackingInfo)
              ?.replaceAll('${refundMoney10}', (_tableData[i]['tongtoolOrderList'][0].TOTALPRICE * 0.1).toFixed(2))
              ?.replaceAll('${refundMoney20}', (_tableData[i]['tongtoolOrderList'][0].TOTALPRICE * 0.2).toFixed(2))
              ?.replaceAll('${refundMoney25}', (_tableData[i]['tongtoolOrderList'][0].TOTALPRICE * 0.25).toFixed(2))
              ?.replaceAll('${refundMoney30}', (_tableData[i]['tongtoolOrderList'][0].TOTALPRICE * 0.3).toFixed(2))
              ?.replaceAll('${refundMoney50}', (_tableData[i]['tongtoolOrderList'][0].TOTALPRICE * 0.5).toFixed(2))
              ?.replaceAll('${refundMoney80}', (_tableData[i]['tongtoolOrderList'][0].TOTALPRICE * 0.8).toFixed(2))
              ?.replaceAll('${refundMoney100}', (_tableData[i]['tongtoolOrderList'][0].TOTALPRICE * 1).toFixed(2))
          }
        }
        setTableData(_tableData)
      }
      setGetMailsDetailLoading(false)
    })
    return () => {
      window.electron.ipcRenderer.removeAllListeners('m2r-query-single-order')
      window.electron.ipcRenderer.removeAllListeners('m2r-query-all-order')
    }
  }, [tableData])

  useEffect(() => {
    window.electron.ipcRenderer.on('message', (_, type: 'success' | 'error' | 'warning' | 'info', note, duration) => {
      message[type](note, duration)
    })
    return () => {
      window.electron.ipcRenderer.removeAllListeners('message')
    }
  }, [])

  /** 根据邮件列表数据设置表格数据
   * 可以设置的表格数据包括 邮件id、邮箱地址、邮件摘要、当前处理人、邮件标题、接收方、邮件附件
   * 还需要额外获取的表格数据包括 邮件详情、邮件对应的通途订单列表
   */
  const setTableDataByMailListData = () => {
    let records = mailListData.data.records || []
    let _tableData: any[] = []
    for (let i = 0; i < records.length; i++) {
      let mailAnnex: any = []
      _tableData.push({})
      if (records[i].mailList?.length > 0) {
        for (let j = 0; j < records[i].mailList.length; j++) {
          let annexList = JSON.parse(records[i].mailList[j].mailAnnex)
          if (annexList.length > 0) {
            for (let k = 0; k < annexList.length; k++) {
              mailAnnex.push(annexList[k].url)
            }
          }
        }
      }
      _tableData[i]['mailOrderId'] = records[i].mailOrderId
      _tableData[i]['fromMail'] = records[i].fromMail
      _tableData[i]['newMailInfo'] = records[i].newMailInfo
      _tableData[i]['nowAssignmentName'] = records[i].nowAssignmentName
      _tableData[i]['orderTitle'] = records[i].orderTitle
      _tableData[i]['toMail'] = records[i].toMail
      _tableData[i]['mailAnnex'] = structuredClone(mailAnnex)
      _tableData[i]['isRquested'] = false
      _tableData[i]['tongtoolOrderList'] = undefined
      for (let topTypeIndex = 0; topTypeIndex < mailTopTypeOptions.length; topTypeIndex++) {
        let topTypeReg = new RegExp(mailTopTypeOptions[topTypeIndex].rule)
        if (topTypeReg.test(records[i].newMailInfo)) {
          _tableData[i]['topType'] = {
            children: mailTopTypeOptions[topTypeIndex].value,
            label: mailTopTypeOptions[topTypeIndex].value,
            value: mailTopTypeOptions[topTypeIndex].value,
          }
        }
      }
      for (let secondTypeIndex = 0; secondTypeIndex < mailSecondTypeOptions.length; secondTypeIndex++) {
        let topTypeReg = new RegExp(mailSecondTypeOptions[secondTypeIndex].rule)
        if (topTypeReg.test(records[i].newMailInfo)) {
          _tableData[i]['secondType'] = {
            children: mailSecondTypeOptions[secondTypeIndex].value,
            label: mailSecondTypeOptions[secondTypeIndex].value,
            value: mailSecondTypeOptions[secondTypeIndex].value,
          }
        }
      }
      for (let mailTemplateIndex = 0; mailTemplateIndex < mailTemplates.length; mailTemplateIndex++) {
        if (mailTemplates[mailTemplateIndex].topType === _tableData[i].topType?.value && mailTemplates[mailTemplateIndex].secondType === _tableData[i].secondType?.value) {
          _tableData[i]['reply'] = mailTemplates[mailTemplateIndex].template
        }
      }
    }
    setTotal(_tableData.length)
    setTableData(_tableData)
  }

  /**
   * 将表格索引转换为表格数据索引
   * @param rowIndex 表格索引
   */
  const getTableDataIndex = (rowIndex: number) => {
    return rowIndex + ((pagination.current - 1) * pagination.pageSize)
  }

  /** 立即更新表格内容，适用于下拉选择
   * @param rowIndex 行索引
   * @param key 键
   * @param value 值
   */
  const updateTableDataImmediate = (rowIndex: number, key: string, value: any) => {
    const tableDataIndex = getTableDataIndex(rowIndex)
    console.log('updateTableDataImmediate', tableDataIndex, key, value)
    let _tempTableData = structuredClone(tableData)
    _tempTableData[tableDataIndex][key] = value
    if (key === 'topType') {
      let template = (mailTemplates.filter((template) => template.topType === value.value) || []).find((template) => template.secondType === _tempTableData[tableDataIndex].secondType.value) || { template: '' }
      _tempTableData[tableDataIndex].reply = template.template || ''
    }
    if (key === 'secondType') {
      let template = (mailTemplates.filter((template) => template.secondType === value.value) || []).find((template) => template.topType === _tempTableData[tableDataIndex].topType.value) || { template: '' }
      _tempTableData[tableDataIndex].reply = template.template || ''
    }
    setTableData(_tempTableData)
  }

  /** 登录通途后需要设置通途的cookie */
  const setTongtoolCookie = () => {
    window.electron.ipcRenderer.send('r2m-set-tongtool-cookie')
  }

  /** 批量获取邮件提示框 */
  const showGetMailsDetailDialog = () => {
    const getMailsDetailDialog = DialogPlugin({
      header: '你确定要批量获取详情吗？',
      body: <span style={{ color: 'var(--td-error-color-7)', fontWeight: 'bold' }}>将会花费10~30分钟，一旦终止需要重来！</span>,
      theme: 'warning',
      style: {
        width: '400px',
      },
      onConfirm: () => {
        getMailsDetail()
        getMailsDetailDialog.hide()
      },
      onClose: () => {
        getMailsDetailDialog.hide()
      },
      onCloseBtnClick: () => {
        getMailsDetailDialog.hide()
      },
    })
  }

  /** 批量获取邮件的详细信息
   * 即时语系统：邮件内容
   * 通途系统：跟踪单号、款项信息
   * track718：物流信息
   */
  const getMailsDetail = () => {
    setGetMailsDetailLoading(true)
    let mailList = tableData.map((row) => row.fromMail)
    console.log('mailList', mailList)
    window.electron.ipcRenderer.send('r2m-query-all-order', mailList, 2)
  }

  /** 批量发送邮件 */
  const sendMails = () => {
  }

  /** 缓存表格数据 */
  const cacheTableData = () => {
    console.log('tableData', tableData)
    electronStore.set('tableData', tableData)
  }

  /** 显示缓存表格数据提示框 */
  const showCacheTableDataDialog = () => {
    const cacheTableDataDialog = DialogPlugin({
      header: '你确定要缓存表格数据吗？',
      body: <span style={{ color: 'var(--td-error-color-7)', fontWeight: 'bold' }}>缓存后将覆盖之前缓存的数据</span>,
      theme: 'warning',
      style: {
        width: '400px',
      },
      onConfirm: () => {
        cacheTableData()
        cacheTableDataDialog.hide()
      },
      onClose: () => {
        cacheTableDataDialog.hide()
      },
      onCloseBtnClick: () => {
        cacheTableDataDialog.hide()
      },
    })
  }

  /** 显示恢复表格数据提示框 */
  const showRestoreTableDataDialog = () => {
    const restoreTableDataDialog = DialogPlugin({
      header: '你确定要恢复表格数据吗？',
      body: <span style={{ color: 'var(--td-error-color-7)', fontWeight: 'bold' }}>恢复后将覆盖当前表格数据</span>,
      theme: 'warning',
      style: {
        width: '400px',
      },
      onConfirm: () => {
        electronStore.get('tableData').then((res) => {
          if (res && Array.isArray(res)) {
            setTableData(res as any[])
            message.success('恢复数据成功')
          } else {
            message.error('没有缓存的数据，恢复数据失败')
          }
        })
        restoreTableDataDialog.hide()
      },
      onClose: () => {
        restoreTableDataDialog.hide()
      },
      onCloseBtnClick: () => {
        restoreTableDataDialog.hide()
      }
    })
  }

  /** 导出退款记录 */
  const showExportRefundTableDataDialog = () => {
    if (refundTableData.length === 0) {
      message.error('没有可供导出的退款记录')
      return
    }
    const exportRefundTableDataDialog = DialogPlugin({
      header: '导出退款数据',
      body: <span style={{ color: 'var(--td-error-color-7)', fontWeight: 'bold' }}>将导出 {refundTableData.length} 条退款记录</span>,
      theme: 'info',
      style: {
        width: '400px',
      },
      onConfirm: () => {
        ExcelExporter.exportJson(refundTableData, {
          fileName: dayjs().format('YYYY-MM-DD HH:mm:ss') + '-退款记录.xlsx',
          headerMap: {
            '订单号': '订单号',
            '下单日期': '下单日期',
            '通途sku': '通途sku',
            '退款原因': '退款原因',
            '中文产品名': '中文产品名',
            '订单金额': '订单金额',
            '退款金额': '退款金额',
          }
        })
        exportRefundTableDataDialog.hide()
      },
      onClose: () => {
        exportRefundTableDataDialog.hide()
      },
      onCloseBtnClick: () => {
        exportRefundTableDataDialog.hide()
      }
    })
  }

  /** 获取并显示历史邮件列表 */
  const showMailHistoryList = async (row: any, rowIndex: number) => {
    const tableDataIndex = getTableDataIndex(rowIndex)
    console.log('row', row, tableDataIndex)
    setClickedRowIndex(tableDataIndex)
    setMailDetailDrawerVisible(true)
    if (row.mailHistoryList) {
      return
    }
    const res = await getMailHistoryList({
      mailOrderId: row.mailOrderId,
      page: 1,
      limit: 30,
    })
    console.log('res', res)
    if (res.code === 401001) {
      message.error('即时语系统凭证失效，请填写新的Cookie')
      return
    }
    let _tableData = structuredClone(tableData)
    _tableData[tableDataIndex].mailHistoryList = res.data.mailList || []
    setTableData(_tableData)
  }

  /** 显示通途详情
   * 打开的时候向主进程发送请求，获取跟踪单号、物流信息；
   * 如果已经查询到详细信息，则不发送请求，直接展示
   * @param row 行数据
   * @param rowIndex 行索引
   */
  const showTongtoolDetail = async (row: any, rowIndex: number) => {
    const tableDataIndex = getTableDataIndex(rowIndex)
    console.log('row', row, tableDataIndex)
    setClickedRowIndex(tableDataIndex)
    setTongtoolDetailDrawerVisible(true)
    if (row.tongtoolOrderList) {
      return
    }
    window.electron.ipcRenderer.send('r2m-query-single-order', row.fromMail, tableDataIndex)
  }

  /** 完成邮件 */
  const showFinishMailDialog = (row: any, rowIndex: number) => {
    if (finishMailLoading) return
    console.log('rowIndex', rowIndex)
    const finishMialDialog = DialogPlugin({
      header: '你确定要完成邮件吗？',
      theme: 'warning',
      style: {
        width: '400px',
      },
      onConfirm: () => {
        // setTableData(tableData)
        // setTableKey(tableKey + 1)
        console.log(row)
        finishMail({
          mailOrderIds: [row.mailOrderId],
          finished: 1
        })
        finishMailSuccess((res) => {
          console.log(res)
          message.success('操作成功')
        })
        removeMailFromTable(rowIndex)
        finishMialDialog.hide()
      },
      onClose: () => {
        finishMialDialog.hide()
      },
      onCloseBtnClick: () => {
        finishMialDialog.hide()
      },
    })
  }

  /** 分配邮件 */
  const showAssignMailDialog = async (row: any, rowIndex: number) => {
    console.log(row.mailOrderId)
    if (assignMailLoading) return
    console.log('rowIndex', rowIndex)
    const personListRes = await getPersonList({
      ifShowOutline: 0,
      mailOrderIds: [row.mailOrderId],
      keyWords: '',
    })
    if (personListRes.code === 401001) {
      message.error('即时语系统凭证失效，请填写新的Cookie')
      return
    }
    console.log(personListRes)
    const options = personListRes.data.map((item: any) => {
      return {
        label: item.realName,
        value: item.id
      }
    })
    let nowAssignmentId = '1522864228370296833'
    const assignMailDialog = DialogPlugin({
      header: '请选择需要分配的人员',
      body: <Select options={options} defaultValue={nowAssignmentId} onChange={(val) => { nowAssignmentId = val as string}}></Select>,
      theme: 'warning',
      style: {
        width: '400px',
      },
      onConfirm: async () => {
        const res = await assignMail({
          mailOrderIds: [row.mailOrderId],
          nowAssignmentId
        })
        console.log(nowAssignmentId, res)
        if (res.code === 401001) {
          message.error('即时语系统凭证失效，请填写新的Cookie')
          return
        }
        message.success(`分配成功-${row.fromMail}`)
        removeMailFromTable(rowIndex)
        assignMailDialog.hide()
      },
      onClose: () => {
        assignMailDialog.hide()
      },
      onCloseBtnClick: () => {
        assignMailDialog.hide()
      },
    })
  }

  /** 发送邮件 */
  const showSendMailDialog = (row: any, rowIndex: number) => {
    if (checkMailBeforeSendLoading || sendMailLoading) return
    let willSendMail = ('Dear Customer, \n\n' + (row.reply || '') + '\n\nBest Regards, \nCustomer Support')
    const sendMailDialog = DialogPlugin({
      header: '你确定要发送邮件吗？',
      body: <div className={`${styles.sendMailModal}`}>
        <div className={styles.sendMailModalContent}>
          <div className={styles.sendMailModalContentItem}>
            <span>收件人：</span>
            <span>{row.fromMail}</span>
          </div>
          <div className={styles.sendMailModalContentItem}>
            <span>内容：</span>
            <div className='c-pre-wrap-content'>{willSendMail}</div>
          </div>
        </div>
      </div>,
      theme: 'warning',
      style: {
        width: '600px',
      },
      onConfirm: async () => {
        willSendMail = willSendMail.replace(/\n/g, '<br>')
        const checkMailBeforeSendResponse = await checkMailBeforeSend({
          word: willSendMail
        })
        if (checkMailBeforeSendResponse.code > 0) {
          const sendMailResponse = await sendMail({
            mailOrderId: row.mailOrderId,
            mailInfo: willSendMail + "\n<a name=\"JSY_MAIL_TAG\"></a>",
            finished: "2",
            mailAnnex: null,
            ccMail: "",
            ywMailListId: "1936096342353682434"
          })
          if (sendMailResponse.code > 0) {
            message.success('发送成功')
            removeMailFromTable(rowIndex)
            sendMailDialog.hide()
          }
        }
      },
      onClose: () => {
        sendMailDialog.hide()
      },
      onCloseBtnClick: () => {
        sendMailDialog.hide()
      },
    })
  }

  /** 移除邮件 */
  const removeMailFromTable = (rowIndex: number) => {
    let _tableData = structuredClone(tableData)
    const tableDataIndex = getTableDataIndex(rowIndex)
    let fromMail = _tableData[tableDataIndex].fromMail
    _tableData.splice(tableDataIndex, 1)
    setTableData(_tableData)
    setTotal(_tableData.length)
    message.success(`已移除邮件-${fromMail}`)
  }

  /** 删除表格数据
   * 这里的行索引需要转换成表格数据的索引，因为表格数据是分页的
   * @param rowIndex 行索引
   */
  const showDeleteMailDialog = (rowIndex: number) => {

    const sendMailDialog = DialogPlugin({
      header: '你确定要移除邮件吗？',
      theme: 'warning',
      style: {
        width: '400px',
      },
      onConfirm: () => {
        removeMailFromTable(rowIndex)
        sendMailDialog.hide()
      },
      onClose: () => {
        sendMailDialog.hide()
      },
      onCloseBtnClick: () => {
        sendMailDialog.hide()
      },
    })
  }

  const onPageChanage = (pageInfo: PageInfo) => {
    setPagination({
      ...pagination,
      current: pageInfo.current,
      pageSize: pageInfo.pageSize
    })
  }

  /** 手动分页，数据量太大表格会卡顿 */
  const computedCurrentPageTableData = useMemo(() => {
    return tableData.slice((pagination.current - 1) * pagination.pageSize, pagination.current * pagination.pageSize > tableData.length ? tableData.length : pagination.current * pagination.pageSize)
  }, [tableData, pagination])

  const columns: Array<PrimaryTableCol> = [
    {
      colKey: 'fromMail',
      title: '邮件地址',
      align: 'center',
      width: 120,
    },
    {
      colKey: 'newMailInfo',
      title: '邮件内容',
      align: 'center',
      width: 280,
      cell: ({ row, rowIndex }: { row: any, rowIndex: number }) => (
        <div className={`${styles.mailInfo} c-pre-wrap-content`} onClick={() => { showMailHistoryList(row, rowIndex) }}>{row.newMailInfo}</div>
      )
    },
    {
      colKey: 'topType',
      title: '邮件类型',
      align: 'center',
      width: 120,
      cell: ({ row, rowIndex, col }: { row: any, rowIndex: number, col: PrimaryTableCol }) => {
        const { colKey = '' } = col
        return <Select
          value={row[colKey]?.value}
          onChange={(_, context) => { updateTableDataImmediate(rowIndex, colKey, context.option) }}
        >
          {mailTopTypeOptions.map((item) => {
            return <Select.Option key={item.value} value={item.value}>{item.value}</Select.Option>
          })}
        </Select>
      }
    },
    {
      colKey: 'secondType',
      title: '邮件二级类型',
      align: 'center',
      width: 160,
      cell: ({ row, rowIndex, col }: { row: any, rowIndex: number, col: PrimaryTableCol }) => {
        const { colKey = '' } = col
        return <Select
          value={row[colKey]?.value}
          onChange={(_, context) => { updateTableDataImmediate(rowIndex, colKey, context.option) }}
        >
          {(row.topType?.value ? mailSecondTypeOptions.filter((item) => item.extends === row.topType?.value) : []).map((item) => {
            return <Select.Option key={item.value} value={item.value}>{item.value}</Select.Option>
          })}
        </Select>
      }
    },
    {
      colKey: 'reply',
      title: '回复内容',
      align: 'center',
      width: 360,
      cell: ({ row, rowIndex, col }: { row: any, rowIndex: number, col: PrimaryTableCol }) => {
        const { colKey = '' } = col
        return <div className='c-pre-wrap-content'>
          <Textarea
            value={row[colKey]}
            autosize={{ minRows: 5, maxRows: 10 }}
            onChange={(value) => { updateTableDataImmediate(rowIndex, colKey, value) }}
          />
        </div>
      }
    },
    {
      colKey: 'operate',
      title: '操作',
      align: 'center',
      width: 120,
      cell: ({ row, rowIndex }: { row: any, rowIndex: number }) => (
        <div className='tdesign-table-demo__table-operations' onClick={(e) => { e.stopPropagation() }}>
          <div className={styles.tongtoolOperationButtonRow}>
            <Tooltip delay={500} content={'邮件详情'}>
              <div className='table-operate-button' onClick={() => { showMailHistoryList(row, rowIndex) }}>
                <RiMailOpenFill />
              </div>
            </Tooltip>
            <Tooltip delay={500} content={'通途'}>
              <div className='table-operate-button' onClick={() => { showTongtoolDetail(row, rowIndex) }}>
                <RiTruckFill />
              </div>
            </Tooltip>
            <Tooltip delay={500} content={'分配邮件'}>
              <div className='table-operate-button' onClick={() => { showAssignMailDialog(row, rowIndex) }}>
                <RiAccountPinCircleFill />
              </div>
            </Tooltip>
          </div>
          <div className={styles.mailOperationButtonRow}>
            <Tooltip delay={500} content={'完成邮件'}>
              <div className='table-operate-button' onClick={() => { showFinishMailDialog(row, rowIndex) }}>
                <RiMailCheckFill />
              </div>
            </Tooltip>
            <Tooltip delay={500} content={'发送邮件'}>
              <div className='table-operate-button' onClick={() => { showSendMailDialog(row, rowIndex) }}>
                <RiSendPlaneFill />
              </div>
            </Tooltip>
            <Tooltip delay={500} content={'移除邮件'}>
              <div className='table-operate-button' onClick={() => { showDeleteMailDialog(rowIndex) }}>
                <RiDeleteBin6Fill />
              </div>
            </Tooltip>
          </div>
        </div>
      )
    }
  ]

  const memoTongtoolDetailDrawer = useMemo(() => {
    return <TongtoolDetailDrawer
      visible={tongtoolDetailDrawerVisible}
      orderInfo={tableData[clickedRowIndex]}
      rowIndex={clickedRowIndex}
      setTableData={setTableData}
      onClose={() => { setTongtoolDetailDrawerVisible(false) }}
      setRefundTableData={setRefundTableData}
    />
  }, [tongtoolDetailDrawerVisible, tableData, clickedRowIndex])

  const memoMailDetailDrawer = useMemo(() => {
    return <MailDetailDrawer
      visible={mailDetailDrawerVisible}
      orderInfo={tableData[clickedRowIndex]}
      rowIndex={clickedRowIndex}
      setTableData={setTableData}
      onClose={() => { setMailDetailDrawerVisible(false) }}
    />
  }, [mailDetailDrawerVisible, clickedRowIndex, tableData])

  return <div className={styles.Home}>
    <div className={'content-wrapper'}>
      <Loading
        loading={getMailsDetailLoading}
        text="正在批量获取邮件详情，请稍后..."
      >
        <Space
          direction="horizontal"
          size="medium"
        >
          <Button onClick={getMailList} loading={mailListLoading}>获取邮件</Button>
          <Button onClick={setTongtoolCookie}>设置通途Cookie</Button>
          <Button onClick={showGetMailsDetailDialog}>批量获取邮件详情</Button>
          <Button onClick={sendMails}>批量发送邮件</Button>
          <Button onClick={showCacheTableDataDialog}>缓存表格数据</Button>
          <Button onClick={showRestoreTableDataDialog}>恢复表格数据</Button>
          <Button onClick={showExportRefundTableDataDialog}>导出退款数据</Button>
        </Space>
      </Loading>
      <Table
        className='bm-table'
        data={computedCurrentPageTableData}
        columns={columns}
        rowKey={'item.mailOrderId'}
        verticalAlign={'middle'}
        bordered={true}
        showHeader={true}
        tableLayout={'fixed'}
        rowClassName={({ rowIndex }) => `${rowIndex}-class`}
        cellEmptyContent={'--'}
        resizable={false}
        size='small'
        loading={mailListLoading}
        maxHeight={900}
        pagination={{
          defaultCurrent: 1,
          defaultPageSize: pagination.pageSize,
          total,
          showJumper: true,
          size: 'small',
          onChange: onPageChanage,
          onCurrentChange(current, pageInfo) {
            console.log(current, pageInfo, 'onCurrentChange current');
          },
          onPageSizeChange(size, pageInfo) {
            console.log(size, pageInfo, 'onPageSizeChange size');
          },
        }}
        onPageChange={(pageInfo) => {
          console.log(pageInfo, 'onPageChange');
        }}
      />
    </div>
    {memoTongtoolDetailDrawer}
    {memoMailDetailDrawer}
  </div>
}

const KeepAliveComponent = (props: any) => {

  const { t } = useTranslation(['home'])
  const { setMeta } = useMeta()

  useEffect(() => {
    setMeta(t('title'), 'menu-page')
  }, [])

  return <KeepAlive name='home' key='home'>
    <Home
      t={t}
      {...props}
    />
  </KeepAlive>
}


export default KeepAliveComponent
